package com.example.administrator.newxlmedical;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapters.CountAdapter;
import adapters.CountSearchAdapter;
import adapters.CountSpinnerAdapter;
import baseinterface.UsbDeal;
import beans.ComboBean;
import beans.CountGoodsDetailInfoBean;
import beans.GoodsInfoBean;
import beans.GoodsStatisticsBean;
import beans.ItemEntity;
import beans.NewUserInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import dialogs.DateDialog;
import dialogs.ProgressDialog;
import interfaces.MyItemClickListener;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import utils.ActivityUtil;
import utils.DefaultFuzzySearchRule;
import utils.FuzzySearchUtils;
import utils.ObjectSaveUtil;
import utils.ScreenUtils;
import utils.StatisticsSortUtils;
import utils.TimeUtil;
import utils.ToastUtil;
import utils.UsbUtils;

public class CountActivity extends BaseActivity implements UsbDeal {

    @BindView(R.id.tv_count_start_date)
    TextView tvStartDate;
    @BindView(R.id.tv_count_end_date)
    TextView tvEndDate;
    @BindView(R.id.tv_count_search)
    TextView tvSearch;
    @BindView(R.id.rv_count_activity)
    RecyclerView recyclerView;
    @BindView(R.id.fl_count_empty)
    FrameLayout flEmpty;
    @BindView(R.id.et_count_supplier)
    EditText etSupplier;
    @BindView(R.id.iv_common_toolbar_home)
    ImageView ivCommonToolbarHome;
    @BindView(R.id.remind_goods)
    TextView tvGoods;
    @BindView(R.id.iv_count_goods_sort)
    ImageView ivGoodsSort;
    @BindView(R.id.remind_supplier)
    TextView tvSupplier;
    @BindView(R.id.iv_count_supplier_sort)
    ImageView ivSupplierSort;
    @BindView(R.id.rl_count_goods_sort)
    RelativeLayout rlCountGoodsSort;
    @BindView(R.id.rl_count_supplier_sort)
    RelativeLayout rlCountSupplierSort;
    @BindView(R.id.sp_count_spinner)
    Spinner mSpinner;
    @BindView(R.id.remind_size)
    TextView tvSize;
    @BindView(R.id.iv_count_size_sort)
    ImageView ivSizeSort;
    @BindView(R.id.rl_count_size_sort)
    RelativeLayout rlSizeSort;
    @BindView(R.id.ll_count)
    LinearLayout llCount;
    @BindView(R.id.remind_count)
    TextView tvPurchase;
    @BindView(R.id.iv_count_purchases_sort)
    ImageView ivPurchaseSort;
    @BindView(R.id.rl_count_purchases_sort)
    RelativeLayout rlPurchaseSort;
    @BindView(R.id.remind_data_end)
    TextView tvUse;
    @BindView(R.id.iv_count_use_sort)
    ImageView ivUseSort;
    @BindView(R.id.rl_count_use_sort)
    RelativeLayout rlUseSort;
    @BindView(R.id.remind_data_save)
    TextView tvStock;
    @BindView(R.id.iv_count_stock_sort)
    ImageView ivStockSort;
    @BindView(R.id.rl_count_stock_sort)
    RelativeLayout rlStockSort;
    @BindView(R.id.remind_data_return)
    TextView tvReturn;
    @BindView(R.id.iv_count_return_sort)
    ImageView ivReturnSort;
    @BindView(R.id.rl_count_return_sort)
    RelativeLayout rlReturnSort;
    @BindView(R.id.tv_no_return)
    TextView tvNoReturn;
    @BindView(R.id.iv_count_no_return_sort)
    ImageView ivNoReturnSort;
    @BindView(R.id.rl_count_no_return_sort)
    RelativeLayout rlNoReturnSort;
    @BindView(R.id.tv_count_sum_star_data)
    TextView tvSumStarData;
    @BindView(R.id.tv_count_sum_end_data)
    TextView tvSumEndData;
    @BindView(R.id.tv_count_sum_stock)
    TextView tvSumStock;
    @BindView(R.id.tv_count_sum_use)
    TextView tvSumUse;
    @BindView(R.id.tv_count_sum_save)
    TextView tvSumSave;
    @BindView(R.id.tv_count_sum_take_out)
    TextView tvSumTakeOut;
    @BindView(R.id.tv_count_sum_no_return)
    TextView tvSumNoReturn;
    @BindView(R.id.tv_count_export)
    TextView tvExport;
    @BindView(R.id.rl_count)
    RelativeLayout rlCount;


    //    Spinner spCountOperate;
//    @BindView(R.id.sp_count_operate)

    private boolean isSortGoods, isSortSpecification, isSortSupplier, isSortPurchase, isSortUse, isSortStock, isReturn, isNoReturn;
    private int sortGoods, sortSpecification, sortSupplier, sortPurchase, sortUse, sortStock, sortReturn, sortNoReturn;
    private int roleInfoId;
    //用于保存用户自己的厂商code
    private String initManufacturerCode = "";
    //用户查询的厂商code
    private String manufacturerCode = "";
    private String startDate, endDate;
    private CountAdapter adapter;
    public static UsbDeal usbDeal;
    private NewUserInfoBean.DataBean userInfoBean;
    private List<GoodsStatisticsBean.DataBean> list = new ArrayList<>();
    private List<GoodsStatisticsBean.DataBean> sortList = new ArrayList<>();
    private List<GoodsStatisticsBean.DataBean> fuzzyList = new ArrayList<>();
    private List<GoodsStatisticsBean.DataBean> allList = new ArrayList<>();
    private List<GoodsInfoBean> searchList = new ArrayList<>();
    private String[] spinnerData ;
    private boolean isFirst = true;
    private String department;
    private boolean isGoods = true, isSupplier;
    private String supplierName;
    private CountSearchAdapter searchAdapter;
    private boolean isSearch;
    private CountSpinnerAdapter mAdapter;
    private int mPosition;
    private GoodsStatisticsBean bean;
    private int fuzzySearchIndex = 1;
    private DefaultFuzzySearchRule mIFuzzySearchRule;
    private FuzzySearchFilter fuzzySearchFilter;
    private List<ComboBean.DataBean> comboList = new ArrayList<>();
    private String[] split1;
    private int count;
    private String supplier;
    private FileOutputStream outputStream;
    private SharedPreferences sharedPreferences;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_count);
        ButterKnife.bind(this);
    }

    @Override
    public void initView() {
        super.initView();
        usbDeal = this;
        spinnerData = new String[]{"未选择"};
        ComboBean.DataBean bean = new ComboBean.DataBean();
        bean.setID(0);
        comboList.add(bean);

        getData();
        userInfoBean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(CountActivity.this, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        supplierName = userInfoBean.getSupplierName();
        sharedPreferences = ActivityUtil.getSharedPreferences(this);
        adapter = new CountAdapter(CountActivity.this, list);
        roleInfoId = userInfoBean.getRoleInfoId();

        department = NetAddress.deptCode;

        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        recyclerView.setVisibility(View.GONE);

        LinearLayoutManager manager1 = new LinearLayoutManager(this);
        searchAdapter = new CountSearchAdapter(CountActivity.this, searchList);

        endDate = TimeUtil.getShowDate();
        startDate = TimeUtil.getShowDate();
        tvStartDate.setText(startDate);
        tvEndDate.setText(endDate);

        mIFuzzySearchRule = new DefaultFuzzySearchRule();
        fuzzySearchFilter = new FuzzySearchFilter();

        if (!Constants.IS_MOUNTED) {
            tvExport.setEnabled(false);
        } else {
            tvExport.setEnabled(true);
        }

        loadingTask();
    }

    protected void loadingTask() {
        showLoadingView(flEmpty);
        if (roleInfoId != 4) {
            getGoodsStatistics(startDate, endDate, "0", department, manufacturerCode, "");
        } else {
            getManufacturerCode("select * from GoodsInfo where Manufacturer ='" + supplierName + "'");
        }
    }

    @Override
    protected void setListener() {
        super.setListener();

        mAdapter = new CountSpinnerAdapter(this, R.layout.count_spinner_layout, spinnerData);
        mAdapter.setDropDownViewResource(R.layout.spinner_bg);
        // 点击 键盘上的搜索
        etSupplier.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {

                    sort(0);
                    ScreenUtils.closeKeybord(etSupplier, CountActivity.this);
                    search();

                    return true;
                }

                return false;
            }
        });

        mSpinner.setAdapter(mAdapter);
        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                GoodsStatisticsBean.DataBean dataBean = list.get(position);
                CountGoodsDetailInfoBean infoBean = new CountGoodsDetailInfoBean();
                infoBean.setBean(dataBean);
                infoBean.setSum1(bean.getSumPurchaseCount());
                infoBean.setSum2(bean.getSumApplyCount());
                infoBean.setSum3(bean.getSumStockCount());
                infoBean.setSum4(bean.getSumTakeOutCount());
                infoBean.setSum5(bean.getSumNotReturnedCount());
                infoBean.setStarTime(tvStartDate.getText().toString());
                infoBean.setEndTime(tvEndDate.getText().toString());

                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.GOODS_DETIAL_INFO, infoBean);

                Intent intent = new Intent(CountActivity.this, CountGoodsDetialActivity.class);
                intent.putExtra("bundle", bundle);
                startActivity(intent);
            }
        });

        searchAdapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String supplier = searchList.get(position).getManufacturer();
                isSearch = false;
                etSupplier.setText(supplier);
                etSupplier.setSelection(supplier.length());
                searchList.clear();
            }
        });

        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                ToastUtil.showToast(TimeOutActivity.this,position+"");
                mPosition = position;
                mAdapter.setSelectPosition(mPosition);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void getData() {
        showLoadingView(flEmpty);
        GetRetrofit.getInstance().getComboData(NetAddress.token, NetAddress.machineCode, "")
                .enqueue(new Callback<ComboBean>() {
                    @Override
                    public void onResponse(Call<ComboBean> call, Response<ComboBean> response) {
                        ComboBean body = response.body();
                        if (body != null && body.getData() != null && body.getData().size() != 0) {
                            spinnerData = new String[body.getData().size()+1];
                            spinnerData[0] = "未选择";
                            for (int i = 0; i < body.getData().size(); i++) {
                                int index = i;
                                spinnerData[++index] = body.getData().get(i).getPackageName();
                            }
                            comboList.addAll(body.getData());
                        }

                        mAdapter = new CountSpinnerAdapter(CountActivity.this, R.layout.count_spinner_layout, spinnerData);
                        mAdapter.setDropDownViewResource(R.layout.spinner_bg);
                        mSpinner.setAdapter(mAdapter);

                    }
                    @Override
                    public void onFailure(Call<ComboBean> call, Throwable t) {

                    }
                });
    }

    //获取供应商的编码
    private void getManufacturerCode(String sql) {
        GetRetrofit.getInstance().getGoodsInfos(NetAddress.token, NetAddress.machineCode, sql).subscribeOn(Schedulers.io()).groupBy(new Func1<ArrayList<GoodsInfoBean>, Boolean>() {
            @Override
            public Boolean call(ArrayList<GoodsInfoBean> goodsInfoBeen) {
                return goodsInfoBeen == null ? false : goodsInfoBeen.size() > 0;
            }
        }).observeOn(AndroidSchedulers.mainThread()).flatMap(new Func1<GroupedObservable<Boolean, ArrayList<GoodsInfoBean>>, Observable<GoodsInfoBean>>() {
            @Override
            public Observable<GoodsInfoBean> call(GroupedObservable<Boolean, ArrayList<GoodsInfoBean>> booleanArrayListGroupedObservable) {
                if (booleanArrayListGroupedObservable.getKey()) {
                    return booleanArrayListGroupedObservable.flatMap(new Func1<ArrayList<GoodsInfoBean>, Observable<GoodsInfoBean>>() {
                        @Override
                        public Observable<GoodsInfoBean> call(ArrayList<GoodsInfoBean> goodsInfoBeen) {
                            return Observable.from(goodsInfoBeen).first();
                        }
                    });
                } else {
                    hideLoadingView();
                    showEmptyView(flEmpty);
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<GoodsInfoBean>() {
            @Override
            public void call(GoodsInfoBean goodsInfoBean) {
                //用户是供应商,且刚进入统计页面时,保存自己所属厂商的CODE
                if (isFirst) {
                    initManufacturerCode = goodsInfoBean.getManufacturerCode();
                    Log.e(TAG, "call: isFirst   " + initManufacturerCode);
                    isFirst = false;
                }
                manufacturerCode = goodsInfoBean.getManufacturerCode();
                if (roleInfoId != 4) {
                    Log.e(TAG, "call: getGoodsStatistics   " + manufacturerCode);
                    getGoodsStatistics(startDate, endDate, "0", department, manufacturerCode, "");
                } else {
                    if (!manufacturerCode.equals(initManufacturerCode)) {
                        ToastUtil.showToast(CountActivity.this, "您不能查询其他厂商");
                        hideLoadingView();
                        showEmptyView(flEmpty);
                    } else {
                        getGoodsStatistics(startDate, endDate, "0", department, initManufacturerCode, "");
                    }
                }
            }
        }, new MyAction1());
    }

    //startTime和endTime传到日就行
    private void getGoodsStatistics(final String startDate, final String endDate, final String cabinetId, String department, String manufacturerCode, String goods) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("startTime", startDate + " 00:00:00.000");
        paramsMap.put("endTime", endDate + " 23:59:59.000");
        paramsMap.put("cabinetId", cabinetId);
        paramsMap.put("terminalInfoId", NetAddress.terminalInfoId);
        paramsMap.put("department", NetAddress.deptCode);
        paramsMap.put("manufacturerCode", manufacturerCode);
        paramsMap.put("goodsName", goods);
        if (mPosition != 0) {
            paramsMap.put("goodsPackageId", comboList.get(mPosition).getID() + "");
        }else {
            paramsMap.put("goodsPackageId", "0");
        }

        GetRetrofit.getInstance().getGoodsStatistics1(NetAddress.token, NetAddress.machineCode, paramsMap)
                .enqueue(new Callback<GoodsStatisticsBean>() {
                    @Override
                    public void onResponse(Call<GoodsStatisticsBean> call, Response<GoodsStatisticsBean> response) {
                        clearData();
                        GoodsStatisticsBean body = response.body();
                        if (body != null) {
                            List<GoodsStatisticsBean.DataBean> data = body.getData();
                            bean = body;
                            if (data != null && data.size() > 0) {

                                for (int i = 0; i < data.size(); i++) {
                                    GoodsStatisticsBean.DataBean dataBean = data.get(i);
                                    if (roleInfoId == 4) {
                                        if (dataBean.getManufacturer().equals(supplierName)) {
                                            list.add(dataBean);
                                            sortList.add(dataBean);
                                            fuzzyList.add(dataBean);
                                            allList.add(dataBean);
                                        }
                                    } else {
                                        list.add(dataBean);
                                        sortList.add(dataBean);
                                        fuzzyList.add(dataBean);
                                        allList.add(dataBean);
                                    }
                                }
                                if (!isSearch) {
                                    hideLoadingView();
                                    StatisticsSortUtils.sortStatisticsGoodsName(list, true);
                                    adapter.notifyDataSetChanged();
                                    recyclerView.setVisibility(View.VISIBLE);
                                } else {
                                    sendEmptyMessage(HandlerConstant.FUZZY_LOGIN_FIINISH);
                                }
                            } else {
                                clearData();
                                adapter.notifyDataSetChanged();
                                hideLoadingView();
                                showEmptyView(flEmpty);
                            }

                        } else {
                            clearData();
                            adapter.notifyDataSetChanged();
                            hideLoadingView();
                            showEmptyView(flEmpty);
                        }
                        if (!isSearch) {
                            // 设置底部总数
                        }setSumContent();
                    }

                    @Override
                    public void onFailure(Call<GoodsStatisticsBean> call, Throwable t) {
                        clearData();
                        adapter.notifyDataSetChanged();
                        hideLoadingView();
                        showEmptyView(flEmpty);
                        ToastUtil.showToast(CountActivity.this,"Error : " + t.getMessage());
                    }
                });
    }

    private void clearData() {
        list.clear();
        sortList.clear();
        allList.clear();
        fuzzyList.clear();
    }

    private void setSumContent() {
        tvSumStarData.setText(startDate);
        tvSumEndData.setText(endDate);
        if (bean != null) {
            tvSumStock.setText(String.valueOf(bean.getSumPurchaseCount()));
            tvSumSave.setText(String.valueOf(bean.getSumStockCount()));
            tvSumTakeOut.setText(String.valueOf(bean.getSumTakeOutCount()));
            tvSumUse.setText(String.valueOf(bean.getSumApplyCount()));
            tvSumNoReturn.setText(String.valueOf(bean.getSumNotReturnedCount()));
        } else {
            tvSumStock.setText("0");
            tvSumSave.setText("0");
            tvSumTakeOut.setText("0");
            tvSumUse.setText("0");
            tvSumNoReturn.setText("0");
        }

    }

    private void search() {
        startDate = tvStartDate.getText().toString();
        endDate = tvEndDate.getText().toString();
        supplier = etSupplier.getText().toString();
        hideEmptyView();
        showLoadingView(flEmpty);
        if (!TextUtils.isEmpty(supplier)) {
            isSearch = true;
            getGoodsStatistics(startDate, endDate, "0", department, manufacturerCode, "");
            split1 = supplier.split(" ");
        } else {
            if (roleInfoId != 4) {
                getGoodsStatistics(startDate, endDate, "0", department, manufacturerCode, "");
            } else {
                if (!TextUtils.isEmpty(initManufacturerCode)) {
                    getGoodsStatistics(startDate, endDate, "0", department, initManufacturerCode, "");
                } else {
                    hideLoadingView();
                    showEmptyView(flEmpty);
                }
            }
        }
    }

    @OnClick({R.id.tv_count_start_date, R.id.tv_count_end_date, R.id.tv_count_search, R.id.iv_common_toolbar_home,
            R.id.rl_count_goods_sort, R.id.rl_count_supplier_sort, R.id.rl_count_size_sort, R.id.rl_count_purchases_sort,
            R.id.rl_count_use_sort, R.id.rl_count_stock_sort, R.id.rl_count_return_sort, R.id.rl_count_no_return_sort,
            R.id.tv_count_export})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_count_start_date:
                DateDialog dateDialog1 = new DateDialog(CountActivity.this, R.style.dialog, "开始时间", tvStartDate.getText().toString(), new DateDialog.OnClickListener() {
                    @Override
                    public void onClick(Dialog dialog, String date) {
                        String nowTime = TimeUtil.getMillisecondDate();
                        if (TimeUtil.checkTime(date)) {
                            date = nowTime.substring(0, 10);
                        }
                        tvStartDate.setText(date);
                        dialog.cancel();

                    }
                });
                dateDialog1.show();
                break;
            case R.id.tv_count_end_date:
                DateDialog dateDialog = new DateDialog(CountActivity.this, R.style.dialog, "结束时间", tvEndDate.getText().toString(), new DateDialog.OnClickListener() {
                    @Override
                    public void onClick(Dialog dialog, String date) {
                        tvEndDate.setText(date);
                        dialog.cancel();
                    }
                });
                dateDialog.show();
                break;
            case R.id.tv_count_search:
                sort(0);
                ScreenUtils.closeKeybord(etSupplier, CountActivity.this);
                search();
                break;
            case R.id.iv_common_toolbar_home:
                ActivityUtil.jumpToActivity(CountActivity.this, MainActivity.class);
                finish();
                break;
            case R.id.rl_count_goods_sort:
                Log.e(TAG, "onViewClicked: rl_count_goods_sort");
                sort(1);
                break;
            case R.id.rl_count_supplier_sort:
                Log.e(TAG, "onViewClicked: rl_count_supplier_sort");
                sort(2);
                break;
            case R.id.rl_count_size_sort:
                Log.e(TAG, "onViewClicked: rl_count_size_sort");
                sort(3);
                break;
            case R.id.rl_count_purchases_sort:
                Log.e(TAG, "onViewClicked: rl_count_purchases_sort");
                sort(4);
                break;
            case R.id.rl_count_use_sort:
                Log.e(TAG, "onViewClicked: rl_count_use_sort");
                sort(6);
                break;
//            case R.id.rl_count_stock_sort:
//                Log.e(TAG, "onViewClicked: rl_count_stock_sort"  );
//                sort(6);
//                break;

            case R.id.rl_count_return_sort:
                Log.e(TAG, "onViewClicked: rl_count_return_sort");
                sort(5);
                break;

            case R.id.rl_count_no_return_sort:
                Log.e(TAG, "onViewClicked: rl_count_no_return_sort");
                sort(8);
                break;

            case R.id.tv_count_export:
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);

                dialog.setTitle("提示: ");
                dialog.setMessage("确定将统计数据导入U盘吗？");
                dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        progressDialog = new ProgressDialog(CountActivity.this, R.style.dialog, "正在导出数据,请稍后");
                        progressDialog.show();
                        exportData();
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                dialog.show();
                break;
        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortGoods != 2) {
                sortGoods++;
                isSortGoods = !isSortGoods;
                StatisticsSortUtils.sortStatisticsGoodsName(list, isSortGoods);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortList);
            }
        } else {
            sortGoods = 0;
            isSortGoods = false;
        }

        if (type == 2) { // 按供应商排序
            if (sortSupplier != 2) {
                sortSupplier++;
                isSortSupplier = !isSortSupplier;
                StatisticsSortUtils.sortStatisticsGoodsSupplier(list, isSortSupplier);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortList);
            }
        } else {
            sortSupplier = 0;
            isSortSupplier = false;
        }

        if (type == 3) {
            if (sortSpecification != 2) {
                sortSpecification++;
                isSortSpecification = !isSortSpecification;
                StatisticsSortUtils.sortStatisticsGoodsSpecification(list, isSortSpecification);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortList);
            }
        } else {
            sortSpecification = 0;
            isSortSpecification = false;
        }

        if (type == 4) {
            if (sortPurchase != 2) {
                sortPurchase++;
                isSortPurchase = !isSortPurchase;
                StatisticsSortUtils.sortStatisticsGoodsPurchase(list, isSortPurchase);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortList);
            }
        } else {
            sortPurchase = 0;
            isSortPurchase = false;
        }

        if (type == 5) {
            if (sortReturn != 2) {
                sortReturn++;
                isReturn = !isReturn;
                StatisticsSortUtils.sortStatisticsGoodsUse(list, isReturn);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortList);
            }
        } else {
            sortReturn = 0;
            isReturn = false;
        }

        if (type == 6) {
            if (sortUse != 2) {
                sortUse++;
                isSortUse = !isSortUse;
                StatisticsSortUtils.sortStatisticsGoodsStock(list, isSortUse);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortList);
            }
        } else {
            sortUse = 0;
            isSortUse = false;
        }

        if (type == 7) {
            if (sortReturn != 2) {
                sortReturn++;
                isReturn = !isReturn;
                StatisticsSortUtils.sortStatisticsGoodsReturn(list, isReturn);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortList);
            }
        } else {
//            sortReturn = 0;
//            isReturn = false;
        }

        if (type == 8) {
            if (sortNoReturn != 2) {
                sortNoReturn++;
                isNoReturn = !isNoReturn;
                StatisticsSortUtils.sortStatisticsGoodsNoReturn(list, isNoReturn);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortList);
            }
        } else {
//            sortNoReturn = 0;
//            isNoReturn = false;
        }

        setSortColor(this, tvGoods, ivGoodsSort, sortGoods, R.color.textview_default_color);
        setSortColor(this, tvSupplier, ivSupplierSort, sortSupplier, R.color.textview_default_color);
        setSortColor(this, tvSize, ivSizeSort, sortSpecification, R.color.textview_default_color);
        setSortColor(this, tvPurchase, ivPurchaseSort, sortPurchase, R.color.stock);
        setSortColor(this, tvUse, ivUseSort, sortUse, R.color.use);
        setSortColor(this, tvStock, ivStockSort, sortStock, R.color.save);
        setSortColor(this, tvReturn, ivReturnSort, sortReturn, R.color.returns);
        setSortColor(this, tvNoReturn, ivNoReturnSort, sortNoReturn, R.color.not_back);

        adapter.notifyDataSetChanged();
    }

    private void clearSortDate() {
        sortGoods = 0;
        sortSpecification = 0;
        sortSupplier = 0;
        sortPurchase = 0;
        sortUse = 0;
        sortStock = 0;
        sortNoReturn = 0;
        sortReturn = 0;
    }

    private void setSortColor(Context context, TextView tv, ImageView iv, int type, int color) {
        if (type == 0) {
            tv.setTextColor(context.getResources().getColor(color));
//            tv.setTextColor(context.getResources().getColor(R.color.textview_default_color));
            iv.setImageResource(R.mipmap.paixu);
        } else {
            tv.setTextColor(context.getResources().getColor(R.color.date_bg_color));
            if (type == 1) {
                iv.setImageResource(R.mipmap.paixuup);
            } else {
                iv.setImageResource(R.mipmap.paixudown);
            }
        }
    }

    @Override
    public void mounted() {
        tvExport.setEnabled(true);
    }

    @Override
    public void unMounted() {
        tvExport.setEnabled(false);
    }

    private class FuzzySearchFilter extends Filter {

        /**
         * 执行过滤操作,如果搜索的关键字为空，默认所有结果
         */

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            Log.e(TAG, "performFiltering:" + fuzzyList.size());
            List<ItemEntity> dateList = FuzzySearchUtils.fillCountData(fuzzyList, fuzzySearchIndex);
            FilterResults result = new FilterResults();
            List<ItemEntity> filterList = new ArrayList<>();
            for (ItemEntity item : dateList) {
                if (mIFuzzySearchRule.accept(constraint, item.getSourceKey(), item.getFuzzyKey())) {
                    filterList.add(item);
                }
            }
            result.values = filterList;
            result.count = filterList.size();
            return result;
        }

        /**
         * 得到过滤结果
         */
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            List<ItemEntity> mDataList = (List<ItemEntity>) results.values;
            fuzzyList.clear();
            if (mDataList != null && mDataList.size() != 0) {
                int sumPurchaseCount = 0;
                int sumStockCount = 0;
                int sumApplyCount = 0;
                int sumNotReturnedCount = 0;
                for (int i = 0; i < mDataList.size(); i++) {
                    ItemEntity itemEntity = mDataList.get(i);
                    GoodsStatisticsBean.DataBean countBean = itemEntity.getCountBean();
                    sumPurchaseCount += countBean.getPurchaseCount();
                    sumStockCount += countBean.getStockCount();
                    sumApplyCount += countBean.getApplyCount();
                    sumNotReturnedCount += countBean.getNotReturnedCount();
                    fuzzyList.add(countBean);
                }

                bean.setSumApplyCount(sumApplyCount);
                bean.setSumNotReturnedCount(sumNotReturnedCount);
                bean.setSumStockCount(sumStockCount);
                bean.setSumPurchaseCount(sumPurchaseCount);

            } else {
                bean.setSumApplyCount(0);
                bean.setSumNotReturnedCount(0);
                bean.setSumStockCount(0);
                bean.setSumPurchaseCount(0);
            }
            sendEmptyMessage(HandlerConstant.FUZZY_SEARCH);
        }
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);

        switch (msg.what) {

            case HandlerConstant.FUZZY_SEARCH:
                count++;
                if (count == split1.length) {
                    count = 0;
                    for (int i = 0; i < allList.size(); i++) {
                        GoodsStatisticsBean.DataBean dataBean = allList.get(i);
                        if (dataBean.getManufacturer().contains(supplier)) {
                            if (!fuzzyList.contains(dataBean)) {

                                bean.setSumApplyCount(bean.getSumApplyCount() + dataBean.getApplyCount());
                                bean.setSumNotReturnedCount(bean.getSumNotReturnedCount() + dataBean.getNotReturnedCount());
                                bean.setSumStockCount(bean.getSumStockCount() + dataBean.getStockCount());
                                bean.setSumPurchaseCount(bean.getSumPurchaseCount() + dataBean.getPurchaseCount());

                                fuzzyList.add(dataBean);
                            }
                        }
                    }
                    list.clear();
                    sortList.clear();
                    if (fuzzyList.size() != 0) {
                        hideLoadingView();
                        list.addAll(fuzzyList);
                        sortList.addAll(fuzzyList);
                        setSumContent();
                    } else {
                        hideLoadingView();
                        showEmptyView(flEmpty);
                    }
                    Log.e(TAG, "onHandleMessage: ");
                    adapter.notifyDataSetChanged();
                    fuzzySearchIndex = 1;
                    fuzzyList.clear();
                    fuzzyList.addAll(allList);
                } else {
                    fuzzySearchIndex = 2;
                    fuzzySearchFilter.filter(split1[1]);
                }

                break;

            case HandlerConstant.FUZZY_LOGIN_FIINISH:

                if (isSearch) {
                    isSearch = false;
                    fuzzySearchFilter.filter(split1[0]);
                }

                break;

            case HandlerConstant.COUNT_EXPORT_FIINISH:
                ToastUtil.showToast(this, "导出成功!");
                break;

        }

    }

    public void exportData() {
        try {
            //需要导出的excel文件的文件名
            String fileName = tvStartDate.getText().toString() + " 至 " + tvEndDate.getText().toString() + " 统计数据.xls";
            //操作excel的对象
            WritableWorkbook wwb = null;
            //根据当前的文件路径创建统计的文件并且实例化出一个操作excel的对象
            outputStream = new FileOutputStream(UsbUtils.getUsbPath() + "/" + fileName);
            wwb = Workbook.createWorkbook(outputStream);
            Log.e("TAG", "exportData: " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + fileName);
            if (wwb != null) {
                String departments = sharedPreferences.getString(Constants.HOSPITAL_DEPARTMENTS, "");
                //创建底部的选项卡  传参是选项卡的名称  和  选型卡的索引
                WritableSheet writableSheet = wwb.createSheet("统计详情", 0);
                Label label = new Label(0, 0, tvStartDate.getText().toString() + " 至 " + tvEndDate.getText().toString() + "   " + departments + " 统计数据");
                writableSheet.addCell(label);
                //创建excel的表头的信息
                String[] topic = {"物品名", "规格", "供应商", "入库", "库存", "使用", "未归"};
                for (int i = 0; i < topic.length; i++) {
                    //横向的在单元格中填写数据
                    Label labelC = new Label(i, 2, topic[i]);
                    writableSheet.addCell(labelC);
                }
                //从实体中遍历数据并将数据写入excel文件中
                ArrayList<String> li;
                int size = list.size();
                for (int j = 0; j < size; j++) {
                    //将数据源列表中的数据整合成 一个个的字符串列表
                    GoodsStatisticsBean.DataBean dataBean = list.get(j);
                    li = new ArrayList<>();
                    li.add(dataBean.getGoodName());
                    li.add(dataBean.getSpecification());
                    li.add(dataBean.getManufacturer());
                    li.add(dataBean.getPurchaseCount() + "");
                    li.add(dataBean.getStockCount() + "");
                    li.add(dataBean.getApplyCount() + "");
                    li.add(dataBean.getNotReturnedCount() + "");
                    int k = 0;
                    for (String l : li) {
                        //将单个的字符串列表横向的填入到excel表中
                        Label labelC = new Label(k, j + 3, l);
                        k++;
                        writableSheet.addCell(labelC);
                    }
                    li = null;
                }
                li = new ArrayList<>();
                li.add("总数");
                li.add("");
                li.add("");
                li.add(bean.getSumPurchaseCount() + "");
                li.add(bean.getSumStockCount() + "");
                li.add(bean.getSumApplyCount() + "");
                li.add(bean.getSumNotReturnedCount() + "");
                int k = 0;
                for (String l : li) {
                    //将单个的字符串列表横向的填入到excel表中
                    Label labelC = new Label(k, size + 4, l);
                    k++;
                    try {
                        writableSheet.addCell(labelC);
                    } catch (WriteException e) {
                        e.printStackTrace();
                    }
                }

            }
            //将文件从内存写入到文件当中
            wwb.write();
            wwb.close();
            outputStream.close();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    sendEmptyMessage(HandlerConstant.COUNT_EXPORT_FIINISH);
                    progressDialog.cancel();
                }
            }).start();

            Log.e(TAG, "exportData: finish");
        } catch (Exception e) {
            ToastUtil.showToast(CountActivity.this, "导出失败!");
            Log.e("TAG", "exportData: wwb失败 ");
            progressDialog.cancel();
            e.printStackTrace();
        }
    }
}
